<?php

namespace App\Http\Controllers\Front;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ApiController;
use App\Models\ShopBalanceLog;
use App\Models\Product;
use App\Models\Order;
use Carbon\Carbon;
use EasyWeChat;
use Log;

class PaymentController extends ApiController
{

    public function wxpayNotify(Request $request)
    {
        $response = EasyWeChat::payment()->handlePaidNotify(function ($notify, $fail) {
            $out_trade_no = $notify['out_trade_no']; // 商户订单号
            $trade_no = $notify['transaction_id'];  // 微信支付订单号
            $order = Order::where('order_no', $out_trade_no)->first();

            if (!$order) {
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            if ($order->status !== Order::STATUS_UNPAID) {
                return true; // 未支付状态的才能支付
            }

            if ($notify['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($notify, 'result_code') === 'SUCCESS') {
                    //加入自己支付完成后该做的事
                    $order->status = Order::STATUS_PAID;
                    $order->payment_status = Order::STATUS_PAID;
                    $order->paid_at = Carbon::now();
                    $order->escrow_trade_no = $trade_no;
                    $order->save();
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true;
        });

        return $response;
    }
}
